$(function () {


    $("#jqGrid").jqGrid({
        url: '../sysorderdeviceinfo/list',     // 请求后台json数据的url
        datatype: "json",
        /*   cellEdit:true,// 后台返回的数据格式
           cellsubmit:'remote',
           cellurl:'../sysorderdeviceinfo/updatedeviceid',*/
        // 列表标题及列表模型
        colModel: [
            {label: '设备序号', name: 'deviceseqno', index: 'DEVICESEQNO', width: 50, key: true},
            {label: '批次', name: 'batchid', index: 'BATCHID', width: 80},
            {label: '厂商', name: 'vendorname', index: 'vendorname', width: 80},
            // {label: '类型', name: 'devicetype', index: 'DEVICETYPE', width: 80, formatter: vm.customFmatterType},
            {label: '设备编号', name: 'deviceid', index: 'DEVICEID', width: 80, editable: true},
            {label: '内线号码', name: 'zwannumber', index: 'ZWANNUMBER', width: 80, editable: true},
            {label: '内线密码', name: 'password', index: 'PASSWORD', width: 80, editable: true},
            {label: '状态', name: 'devicestatus', index: 'DEVICESTATUS', width: 80, formatter: vm.customFmatterStatus},
            {label: '描述', name: 'devicedesc', index: 'DEVICEDESC', width: 80}
        ],
        viewrecords: true,     // 是否显示行号，默认值是false，不显示
        height: 385,            // 表格高度
        rowNum: 50,             // 一页显示的行记录数
        rowList: [50, 100],     // 翻页控制条中 每页显示记录数可选集合
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",          // 翻页DOM
        jsonReader: {                   // 重写后台返回数据的属性
            root: "page.list",          // 将rows修改为page.list
            page: "page.currPage",      // 将page修改为page.currPage
            total: "page.totalPage",    // 将total修改为page.totalPage
            records: "page.totalCount"  // 将records修改为page.totalCount
        },
        /*   beforeSubmitCell:function(rowid, cellname, value, iRow, iCol){
             console.log(getSelectedRow());
           },
           afterSubmitCell:function(serverresponse, rowid, cellname, value, iRow, iCol){
               if(serverresponse.code === 0){
                   alert('操作成功', function(rowid){
                       vm.reload();
                   });
               }else{
                   alert(serverresponse.msg);
               }
           },*/

        prmNames: {              // 改写请求参数属性
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            //设置高度
            $("#jqGrid").jqGrid('setGridHeight', getWinH());
        }
    });

    $.get("../companyinfo/companyList/", function (r) {
        vm.companyList = r.data;
        //  $(".js-example-basic-single").select2();
        if (r.code == 0) {

            var data = r.data;
            var optionstring = "";
            for (var i in data) {
                var jsonObj = data[i];


                // $("#vendor").append("<option value=\"" + jsonObj.DEVICEVENDORID + "\" >" + jsonObj.VENDORNAME + "</option>");
                optionstring += "<option value=\"" + jsonObj.COMPANYID + "\" >" + jsonObj.COMPANYNAME + "</option>";

                $("#companylists").html("<option value='请选择'>请选择...</option> " + optionstring);
            }

        }
    });
    $.get("../devicevendor/vendors", function (r) {
        if (r.code == 0) {
            vm.vendors = r.vendors;
        } else {
            alert("获取厂商信息出错！！！");
        }
    });

});

Vue.use(VeeValidate);

var vm = new Vue({
    el: '#rrapp',
    data: {
        options: {},
        companyList: {},
        vendors: {},
        showList: true,
        showid: true,
        title: null,
        sysorderdeviceinfo: {},
        bindcompany: {},
        devicevendormap: {},
        bindmodal: false,
        listok: false
    },
    methods: {
        query: function () {

            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    keyword: $("#keyword").val()
                },
                page: 1
            }).trigger("reloadGrid");
        },
        add: function () {
            // var ok = vm.addVendors();
            console.log(vm.vendors);
            vm.showList = false;
            vm.title = "新增";
            vm.showid = false;
            vm.sysorderdeviceinfo = {};
        },
        update: function (event) {
            var deviceseqno = getSelectedRow();

            if (deviceseqno == null) {
                return;
            }


            vm.getInfo(deviceseqno);
            vm.showList = false;
            vm.showid = true;
            vm.title = "修改";


        },
        saveOrUpdate: function (event) {
            if (!$("#addform").validationEngine('validate')) {
                return false;
            }
            var url = vm.sysorderdeviceinfo.deviceseqno == null ? "../sysorderdeviceinfo/save" : "../sysorderdeviceinfo/update";

            if (vm.sysorderdeviceinfo.deviceseqno == null) {
                if (vm.sysorderdeviceinfo.deviceid != null) {
                    var result = null;
                    $.get("../sysorderdeviceinfo/findByDeviceId/" + vm.sysorderdeviceinfo.deviceid, function (r) {
                        if (r.data != null) {
                            alert("系统中已存在该设备的ID,请确认后添加!!!!!");
                        } else {
                            $.ajax({
                                type: "POST",
                                url: url,
                                data: JSON.stringify(vm.sysorderdeviceinfo),
                                success: function (r) {
                                    if (r.code === 0) {
                                        alert('操作成功', function (index) {
                                            vm.reload();
                                        });
                                    } else {
                                        alert(r.msg);
                                    }
                                }
                            });
                        }
                    });


                }

            } else {
                var deviceseqno = getSelectedRow();
                var rowData = $("#jqGrid").getRowData(getSelectedRow());
                var deviceid = rowData.deviceid;
                var company = {};
                if (deviceid == null || deviceid == undefined || deviceid == '') {
                    alert("请维护设备编号！！！");
                } else {

                    if (vm.sysorderdeviceinfo.deviceid != deviceid) {
                        $.get("../sysorderdeviceinfo/queryBindCompany/", {"deviceid": deviceid}, function (r) {
                            company = r.data;
                            console.log(company);
                            if (company == null) {

                                $.ajax({
                                    type: "POST",
                                    url: url,
                                    data: JSON.stringify(vm.sysorderdeviceinfo),
                                    success: function (r) {
                                        if (r.code === 0) {
                                            alert('操作成功', function (index) {
                                                vm.reload();
                                            });
                                        } else {
                                            alert(r.msg);
                                        }
                                    }
                                });
                            }
                            else {
                                alert("该设备已绑定企业：" + company.COMPANYID + " ，" + company.COMPANYNAME);
                            }
                        });
                    } else {

                        $.ajax({
                            type: "POST",
                            url: url,
                            data: JSON.stringify(vm.sysorderdeviceinfo),
                            success: function (r) {
                                if (r.code === 0) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }


                    //vm.sysorderdeviceinfo.devicevendorid = $("#vendor").val();

                }
            }
        }
        ,
        del: function (event) {
            var deviceseqnos = getSelectedRows();
            if (deviceseqnos == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../sysorderdeviceinfo/delete",
                    data: JSON.stringify(deviceseqnos),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        }
        ,
        getInfo: function (deviceseqno) {
            $.get("../sysorderdeviceinfo/info/" + deviceseqno, function (r) {
                vm.sysorderdeviceinfo = r.sysorderdeviceinfo;
                console.log(r.sysorderdeviceinfo);
                //更新输入框高度
                autosize.update($('textarea'));
            });
        }
        ,
        viewbind: function () {
            var rowData = $("#jqGrid").getRowData(getSelectedRow());
            var deviceid = rowData.deviceid;
            $.get("../sysorderdeviceinfo/queryBindCompany/", {"deviceid": deviceid}, function (r) {

                vm.bindcompany = r.data;
                console.log(vm.bindcompany);
                $('#myModal').modal({
                    keyboard: true
                });
            });
        }
        ,

        customFmatter: function (cellvalue, options, rowObject) {
            $.each(vm.vendors, function (i, val) {
                if (cellvalue == val.DEVICEVENDORID) {
                    cellvalue = val.VENDORNAME;
                }
            });
            return cellvalue;
        }
        ,

        customFmatterType: function (cellvalue, options, rowObject) {
            switch (cellvalue) {
                case 1:
                    return "IP总机";
                case 2:
                    return "软电话";
                case 101:
                    return "HX411-1S/1O_单口语音网关";
                case 102:
                    return "MX8-2S/2O_双口语音网关";
                case 103:
                    return "MX8-4S/4O_4口语音网关";
                case 201:
                    return "C01_VOIP座席电话";
                case 202:
                    return "BW210_VOIP语音电话";
                case 203:

                    return "D800_VOIP视频电话";
                case 301:
                    return "智能眼镜";
                case 302:
                    return "观看端";
            }
        }
        ,

        customFmatterStatus: function (cellvalue, options, rowObject) {
            switch (cellvalue) {
                case 0:
                    return "待测试";
                case 1:
                    return "入库";
                case 2:
                    return "返厂维修";
                case 3:
                    return "待发货";
                case 4:
                    return "已发货";
                case 5:
                    return "已收货";
                case 6:
                    return "在网运行";
                case 7:
                    return "报废";

            }
        }
        ,

        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page
            }).trigger("reloadGrid");
        }
        ,
        vendors: function () {
            /* $.get("../sysdevicevendor/allList/", function (r) {
                 vm.options = r.data;
             });*/
        }
        ,
        /*    addVendors: function () {
                $.get("../sysdevicevendor/allList/", function (r) {
                    vm.options = r.data;
                    //  $(".js-example-basic-single").select2();
                    if (r.code == 0) {
                        /!*$("#vendor").select2();*!/
                        vm.listok = true;
                    }

                    /!*  var data = r.data;
                      console.log(data);
                      for (var i in data) {
                          var jsonObj =data[i];
                          var optionstring = "";
                          console.log( $("#vendor"));

                         // $("#vendor").append("<option value=\"" + jsonObj.DEVICEVENDORID + "\" >" + jsonObj.VENDORNAME + "</option>");
                          optionstring += "<option value=\"" + jsonObj.vendorcode + "\" >" + jsonObj.vendorname + "</option>";


                         // $("#vendor").html("<option value='请选择'>请选择...</option> "+optionstring);
                      }*!/
                });


            },*/
        bindcompany1: function () {
            $('#bindcompanymodal').modal({
                keyboard: true
            });

        }
        ,
        delCC: function () {
            vm.bindmodal = true;
            vm.ccdevice();
            $('#ccModal').modal({
                keyboard: true
            });

        }
        ,
        bindCC: function () {
            var deviceseqno = getSelectedRow();
            var rowData = $("#jqGrid").getRowData(getSelectedRow());
            var bindcc = getGridSelectedRow('jqGridCC');
            var rowDataBind = $("#jqGridCC").getRowData(bindcc);
            var zwannumber = rowDataBind.zwannumber;
            var deviceId = rowData.deviceid;
            if (!typeof(rowData.zwannumber) == "undefined" && rowData.zwannumber == rowDataBind.zwannumber) {
                console.log(rowData.zwannumber);
                alert("对不起，这是您自己的视频号码！！！");
            } else {
                var deviceCc = {"deviceid": '', "callNo": ''};
                deviceCc.deviceid = deviceId;
                deviceCc.callNo = zwannumber;
                if (deviceId != null && zwannumber != null) {
                    $.ajax({
                        type: "POST",
                        url: "../devicecc/save",
                        data: JSON.stringify(deviceCc),
                        success: function (r) {
                            if (r.code == 0) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                                $('#ccModal').modal('hide');
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                } else {
                    alert("请选中！！！");
                }

            }


        }
        ,
        setCC: function () {
            vm.bindmodal = true;
            vm.ccdevice();


            $('#ccModal').modal({
                keyboard: true

            });

            /* $("#jqGridCC").jqGrid('setGridWidth', $("#ccModal").width()/2).jqGrid('setGridHeight', 500);*/


        }
        ,

        ccdevice: function () {

            $("#jqGridCC").jqGrid({
                url: '../sysorderdeviceinfo/list',     // 请求后台json数据的url
                datatype: "json",
                /*   cellEdit:true,// 后台返回的数据格式
                   cellsubmit:'remote',
                   cellurl:'../sysorderdeviceinfo/updatedeviceid',*/
                // 列表标题及列表模型
                colModel: [

                    {label: '批次', name: 'batchid', index: 'BATCHID', width: 80},
                    {label: '设备编号', name: 'deviceid', index: 'DEVICEID', width: 80, editable: true},
                    {label: '内线号码', name: 'zwannumber', index: 'ZWANNUMBER', width: 80, editable: true},
                    {label: '描述', name: 'devicedesc', index: 'DEVICEDESC', width: 80}
                ],
                viewrecords: true,     // 是否显示行号，默认值是false，不显示
                height: 385,            // 表格高度
                rowNum: 50,             // 一页显示的行记录数
                rowList: [50, 100],     // 翻页控制条中 每页显示记录数可选集合
                rownumbers: true,
                rownumWidth: 25,
                autowidth: true,
                multiselect: true,
                pager: "#jqGridPagerCC",          // 翻页DOM
                jsonReader: {                   // 重写后台返回数据的属性
                    root: "page.list",          // 将rows修改为page.list
                    page: "page.currPage",      // 将page修改为page.currPage
                    total: "page.totalPage",    // 将total修改为page.totalPage
                    records: "page.totalCount"  // 将records修改为page.totalCount
                },
                /*   beforeSubmitCell:function(rowid, cellname, value, iRow, iCol){
                     console.log(getSelectedRow());
                   },
                   afterSubmitCell:function(serverresponse, rowid, cellname, value, iRow, iCol){
                       if(serverresponse.code === 0){
                           alert('操作成功', function(rowid){
                               vm.reload();
                           });
                       }else{
                           alert(serverresponse.msg);
                       }
                   },*/

                prmNames: {              // 改写请求参数属性
                    page: "page",
                    rows: "limit",
                    order: "order"
                },
                gridComplete: function () {
                    //隐藏grid底部滚动条
                    /* $("#jqGridCC").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                     $("#jqGridCC").closest(".ui-jqgrid-hdiv").css({width: "100%"});*/

                    $("#jqGridCC").setGridWidth($("#ccModal").width() / 2);

                }
            });
        },

        queryCC: function () {
            $("#jqGridCC").jqGrid('setGridParam', {
                postData: {
                    keyword: $("#keywordCC").val()
                },
                page: 1
            }).trigger("reloadGrid");
        },
        hello: function () {
            alert("hello world");

        }
        ,
        activeDevice: function () {
            var deviceseqno = getSelectedRow();
            var rowData = $("#jqGrid").getRowData(getSelectedRow());
            var deviceid = rowData.deviceid;
            var company = {};
            if (deviceid == null || deviceid == undefined || deviceid == '') {
                alert("请维护设备编号！！！");
            } else {
                $.get("../sysorderdeviceinfo/queryBindCompany/", {"deviceid": deviceid}, function (r) {

                    company = r.data;
                    console.log(company);
                    if (company == null) {

                        var params = {
                            "companyid": "",
                            "devicevendorid": "",
                            "devicetype": "",
                            "deviceid": ""
                        };
                        // params.companyid = getSelectedRow();
                        var device = {};
                        $.get("../sysorderdeviceinfo/info/" + deviceseqno, function (r) {
                            device = r.sysorderdeviceinfo;
                            console.log(device);

                            params.devicevendorid = device.devicevendorid;
                            params.devicetype = device.devicetype;
                            params.deviceid = rowData.deviceid;
                            var companyid = $("#companylists").val();
                            console.log(companyid);
                            console.log(params);

                            $.ajax({
                                url: "../companyinfo/activeDevice",
                                data: {
                                    companyid: companyid,
                                    devicevendorid: params.devicevendorid,
                                    devicetype: params.devicetype,
                                    deviceid: params.deviceid
                                },
                                success: function (r) {
                                    if (r.code == 0) {
                                        alert('操作成功', function (index) {
                                            vm.reload();
                                        });
                                        $('#bindcompanymodal').modal('hide');
                                    } else {
                                        alert(r.msg);
                                    }
                                }
                            });
                        });

                    } else {
                        alert("该设备已绑定企业：" + company.COMPANYID + " ，" + company.COMPANYNAME);
                    }


                });

            }


        },
        pageSize: function () {
            var winW, winH;
            if (window.innerHeight) {// all except IE
                winW = window.innerWidth;
                winH = window.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) {// IE 6 Strict Mode
                winW = document.documentElement.clientWidth;
                winH = document.documentElement.clientHeight;
            } else if (document.body) { // other
                winW = document.body.clientWidth;
                winH = document.body.clientHeight;
            }  // for small pages with total size less then the viewport
            return {WinW: winW, WinH: winH};

        }

    }
});


// 图片自适应


// textarea 高度自动扩展
autosize($('textarea'));